import axios from "axios";
import { showSuccessToast, showFailToast } from 'vant';
import { debounce } from "throttle-debounce";
import router from "./router";

const confirmMessage = debounce(1000, (message) => {
    showFailToast(message);
});

const service = axios.create({
    baseURL: '/xjwxx/v1',
    timeout: 186000,
});

// 请求拦截器
service.interceptors.request.use(
    (config) => {
        const isUrl = config.url.slice(1, 7) //config.url.slice(1, config.url.length );
  
        const whiteUrls = ['/audio-to-text']//['audio-to-text', 'conversations', 'messages', 'text-to-audio','getAimodelList'];
        const isToken = whiteUrls.includes(config.url);
        console.log(config.url, isToken)
        config.baseURL = (isToken) ? 'jiucheng' : '/xjwxx/v1' //'http://192.168.0.33:30060/v1'
       
        // 1. 处理授权Token
        const token = sessionStorage.getItem('token');
        if (!config.headers['Authorization'] && config.url !== '/login') {
            config.headers['Authorization'] = !isToken ? `Bearer ${token}` : 'Bearer app-wX3wQORoF2qu6M9Y9WlzJcNe'//`Bearer ${sessionStorage.getItem('modelToken')}`//'Bearer app-XwwVQh7FebzZN7Jbjh4uUL8v';
        }
        // 2. 智能处理Content-Type
        if (!config.headers['Content-Type']) {
            if (config.data instanceof FormData) {
                config.headers['Content-Type'] = 'multipart/form-data';
            } else if (config.data instanceof Blob) {
                config.headers['Content-Type'] = config.data.type || 'application/octet-stream';
            } else {
                config.headers['Content-Type'] = 'application/json';
            }
        }

        // 3. 数据转换（非FormData/Blob类型）
        if (!(config.data instanceof FormData) &&
            !(config.data instanceof Blob) &&
            config.headers['Content-Type'] === 'application/json') {
            config.data = JSON.stringify(config.data);
        }

        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    (response) => {
        const statusHandlers = {
            200: (res) => {
                if (res.data.code === 200 || !res.data.code) {
                    return res.data;
                } else {
                    confirmMessage(res.data.msg);
                     return Promise.reject(res.data);
                }
            },
            400: (res) => {
                confirmMessage(res.data?.errmsg || '请求参数错误');
                return Promise.reject(res.data);
            },
            401: (res) => {
                sessionStorage.removeItem('token');
                confirmMessage("您的授权已过期，请登录系统");
                router.push("/login");
                return Promise.reject(res.data);
            },
            403: (res) => {
                confirmMessage("亲！您没有权限操作此项");
                return Promise.reject(res.data);
            },
            404: (res) => {
                confirmMessage("资源不存在");
                return Promise.reject(res.data);
            },
            426: (res) => {
                confirmMessage("用户名或密码错误");
                return Promise.reject(res.data);
            },
            500: (res) => {
                confirmMessage(res.data?.errmsg || "网络错误");
                return Promise.reject(res.data);
            },
            502: (res) => {
                confirmMessage(res.data?.errmsg || "服务不可用");
                return Promise.reject(res.data);
            },
            503: (res) => {
                confirmMessage("服务器维护中");
                return Promise.reject(res.data);
            }
        };

        const handler = statusHandlers[response.status] || ((res) => {
            confirmMessage(res.data?.msg || `未知错误: ${response.status}`);
            return Promise.reject(res.data);
        });

        return handler(response);
    },
    (error) => {
        if (error.response) {
            // 有响应但状态码不在2xx范围内
            const status = error.response.status;
            const defaultMessages = {
                400: "请求参数错误",
                401: "您的授权已过期，请登录系统",
                403: "没有权限操作此项",
                404: "资源不存在",
                500: "服务器内部错误",
                502: "网关错误",
                503: "服务不可用",
                504: "网关超时"
            };

            const message = error.response.data?.errmsg ||
                defaultMessages[status] ||
                `请求失败: ${status}`;

            confirmMessage(message);

            if (status === 401) {
                sessionStorage.removeItem('token');
                router.push("/login");
            }
        } else if (error.request) {
            // 请求已发出但没有收到响应
            confirmMessage("网络连接异常，请检查网络");
        } else {
            // 请求配置出错
            confirmMessage("请求配置错误: " + error.msg);
        }

        return Promise.reject(error);
    }
);

// 封装专用文件上传方法
// service.upload = function (url, file, data = {}, config = {}) {
//     const formData = new FormData();
//     formData.append('file', file);

//     Object.keys(data).forEach(key => {
//         formData.append(key, data[key]);
//     });

//     return this.post(url, formData, {
//         ...config,
//         headers: {
//             'Content-Type': 'multipart/form-data',
//             ...config.headers
//         }
//     });
// };

export default service;